package com.jsjosem.aftersales.ui;

import static com.jsjosem.aftersales.constant.CommonConstant.LOGIN_USER;
import static com.jsjosem.aftersales.constant.CommonConstant.USER_INFO;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.google.gson.Gson;
import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.api.UserApi;
import com.jsjosem.aftersales.cache.UserCache;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.LoginUserResponse;
import com.jsjosem.aftersales.databinding.ActivityStartBinding;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.ui.login.LoginActivity;
import com.wang.avi.AVLoadingIndicatorView;

import java.time.LocalDateTime;
import java.util.Objects;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import retrofit2.Call;
import retrofit2.Retrofit;

public class StartActivity extends AppCompatActivity {

    private ActivityStartBinding binding;

    private UserCache userCache;

    private SharedPreferences sp;

    private ConstraintLayout view;

    private TextView tvContinue;

    private AVLoadingIndicatorView avi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityStartBinding.inflate(getLayoutInflater());
        view = binding.getRoot();
        tvContinue = view.findViewById(R.id.tv_continue);
        avi = view.findViewById(R.id.avi);
        // 判断用户登录信息是否过期，如果没有过期，直接到主页面
        sp = getSharedPreferences(USER_INFO, Context.MODE_PRIVATE);
        String loginUserJson = sp.getString(LOGIN_USER, null);
        if (StrUtil.isNotBlank(loginUserJson)) {
            UserCache userCacheLoad = new Gson().fromJson(loginUserJson, UserCache.class);
            this.userCache = UserCache.getInstance();
            this.userCache.setUser(userCacheLoad.getUser());
            this.userCache.setToken(userCacheLoad.getToken());
            this.userCache.setLogin(userCacheLoad.isLogin());
        }

        CountDownTimer start = new CountDownTimer(3000, 1000) {
            /**
             * 倒计时
             * @param millisUntilFinished
             */
            public void onTick(long millisUntilFinished) {
                tvContinue.setText(millisUntilFinished / 1000 + " 跳过");
            }

            /**
             * 倒计时结束跳转到对应页面
             */
            public void onFinish() {
                startActivity();
            }
        }.start();

        tvContinue.setOnClickListener(view -> {
            // 结束倒计时
            start.cancel();
            startActivity();
        });

        setContentView(view);
        avi.show();
    }

    private void startActivity() {
        if (Objects.isNull(userCache) || !userCache.isLogin()) {
            startLoginActivity();
            return;
        }
        Retrofit retrofit = RetrofitClient.getInstance();
        UserApi userApi = retrofit.create(UserApi.class);
        Call<BaseResponse<LoginUserResponse>> loginUserInfo = userApi.getLoginUserInfo();
        AsyncRequest<BaseResponse<LoginUserResponse>> getLoginUserReq = new AsyncRequest<>();
        getLoginUserReq.sendRequest(loginUserInfo, (userRes) -> {
            LocalDateTime expiredTime = DateUtil.parseLocalDateTime(userRes.getData().getmExpiredTime());
            if (expiredTime.isAfter(LocalDateTime.now())) {
                userCache.getUser().setExpired_at(DateUtil.format(expiredTime, "yyyy-MM-dd HH:mm:ss"));
                startMainActivity();
            } else {
                Toast.makeText(this, "登录过期，请重新登录", Toast.LENGTH_SHORT).show();
                startLoginActivity();
            }
        }, failedMessage -> {
            Toast.makeText(this, failedMessage.toString(), Toast.LENGTH_SHORT).show();
            startLoginActivity();
        });
    }

    /**
     * 只有登陆以后才可以启动主页
     */
    private void startMainActivity() {
        // 启动主页面
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 跳转到登录页
     */
    private void startLoginActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }
}